/*
 * Copy Right @ Alvin Hon, HKUST
 */
var codelist = ['ACCT', 'BIEN','BTEC','CBME','CENG','CHEM','CIEM','CIVL','COMP','CSIT',
  'ECON','EEMT','EESM','ELEC','ENEG','ENGG','ENVR','ENVS','EVNG','EVSM',
  'FINA','FYTG','GBUS','GNED','HART','HLTH','HUMA','IBTM','IELM','ISOM',
  'JEVE','LABU','LAGR','LANG','LIFS','MAFS','MALS','MARK','MATH','MECH',
  'MESF','MGMT','NANO','PDEV','PHYS','RMBI','SBMT','SCED','SCIE','SHSS','SOSC','SSMA','TEMG','UROP'];
var times = [];
var courseStack = [];
var xmlHttp = new XMLHttpRequest();

function sort_uniq(arr){
	var arrs = arr.slice();
	arrs = arrs.sort();
	var arrun = new Array();
	var a = arrs[0];
	arrun.push(a);
	for(i = 1;i<arrs.length;i++){
		if(arrs[i]==a){
			continue;
		}else{
			a = arrs[i];
			arrun.push(a);
		}
	}
	
	return arrun;
}

function readTheFile(evt){
	var f = evt.target.files[0];
	if(!f) {
		alert("fail to read file");
	}else{
		var r = new FileReader();
		r.onload = function(e){
			document.getElementById("coursearea").value = e.target.result;
			var ts = (e.target.result).split("\n");
			var ts0=ts[0].split("\t");
			
			var codes = new Array();
			var names = new Array();
			var sems = new Array();
			var lgrade = new Array();
			var ngrade = new Array();
			
			for(i=0;i<ts.length;i++){
				var tsi = ts[i].split("\t");
				codes.push(tsi[0]);
				names.push(tsi[1]);
				sems.push(tsi[2]);
				lgrade.push(tsi[3]);
				ngrade.push(tsi[4]);
			}
			
			var susems = sort_uniq(sems);
			var susems0  = new Object();
			
			for(i = 0;i<susems.length;i++){
				susems0[susems[i]] = i;
			}
			
			for(i = 0;i<susems.length;i++){
				var uid = 'sortable_'+i;
				$("#courselist").append('<ui class="sortable" id="'+uid+'">'+susems[i]+'</ui>');
			}
			
			for(i = 0;i<ts.length;i++){
				$("#sortable_"+susems0[sems[i]]).append('<li class="sortable_li" id="li_'+i+'">'+codes[i]+'</li>');
			}
			
			$(".sortable_li").click(function(e){
				document.getElementById("thep").innerHTML=e.target.id.match(/\d+/);
			});
			
			
		};
		r.readAsText(f);
	}
}

function getXMLbyCode(code){
	xmlDoc = xmlHttp.responseXML;
	return xmlDoc.getElementsByTagName(code)[0].getElementsByTagName('course');
}

function getIdNameUnit(courseNode){
	var id = courseNode.getAttribute("id");
	var n = courseNode.getElementsByTagName("courseName")[0].childNodes[0].nodeValue;
	var u = courseNode.getElementsByTagName("courseUnit")[0].childNodes[0].nodeValue;
	return [id,n,u];
}

function getSections(courseNode){
	var sescs = courseNode.getElementsByTagName("section");
	var output = [];
	
	for(j = 0;j<sescs.length;j++){
		var o = new Object();
		o['id']=sescs[j].attributes.getNamedItem('id').value;
		var dt = sescs[j].getElementsByTagName('dateTime');
		var dtt = dt[0].textContent;
		for(k=1;k<dt.length;k++){
			dtt = dtt+"<br>"+dt[k].textContent;
		}
		o['dateTime']=dtt;
		//o['dateTime']=sescs[j].getElementsByTagName('dateTime')[0].firstChild.nodeValue;
		o['place']=sescs[j].getElementsByTagName('place')[0].firstChild.nodeValue;
		var pl = sescs[j].getElementsByTagName('prof');
		var plo = []
		for(k=0;k<pl.length;k++){
			plo.push(pl[k].firstChild.nodeValue);
		}
		o['profs']=plo;
		
		output.push(o);
	}
	
	
	return output;
}

function minsDiffs(dastring, dbstring){
	var sed1 = dastring.match(/\d\d/g);
	var sed2 = dbstring.match(/\d\d/g);
	var temp1 = iDate(sed1[0],sed1[1],0);
	var temp2 = iDate(sed2[0],sed2[1],0);
	return Math.abs((temp1 - temp2)/(1000*60));
}

function iAlert(msg){
	var msgid = document.getElementById("msg");
	msgid.innerHTML='<p>'+msg+'</p>';
	$("#msg").dialog("open");
}

function placeBlock(dtstrings,cont1,cont2){
	var splpb = dtstrings.split('<br>');
	
	if(splpb.length>4){
		iAlert("Too many sections. Please refer to official course schedule");
		return nil;	
	}
	
	var identity = randomString();
	for(pbo=0;pbo<splpb.length;pbo++){
		var se = splpb[pbo].match(/\d\d:\d\d(AM|PM)/g);
		
		var se1 = convertADate(se[0]);
		var se2 = convertADate(se[1]);
		var count = -1;
		for(pbi = 0;pbi<times.length;pbi++){
			if(times[pbi]==se1){
				count = pbi;
				break;
			}
		}
		if(count==-1) continue;
		var bHeight = ((minsDiffs(se1,se2)+10)/30) * $("#time-0").height();
		var weeks = [];
		var weektemp = splpb[pbo].match(/(Mo|Tu|We|Th|Fr|Sa)/g);
		for(pbi = 0;pbi<weektemp.length;pbi++){
			var pbdiv= $('<div>',{
				"code":cont1,
				"sec":cont2,
				"class":"block-"+identity,
				"style":'font-size: 0.8em; width:120px; height:'+ bHeight+'px; position: absolute; top:0;',
				text:(cont1+' '+cont2)
			});
			pbdiv.appendTo("#timetable");
			pbdiv.button();
			pbdiv.position({
				of:$('td',"#time-"+count)[weekToNum(weektemp[pbi])],
				my:"left top",
				at:"right top",
				offset:"0 0",
				collision:"none"
			});
			pbdiv.click(function(){
				remvFromSelect(identity,$(this).attr('code'),$(this).attr('sec'))
			});
		}
	}	
}

function remvFromSelect(id12,code12,sec12){
	
	var hascode12 = 0;
	var remvInd = 0;
	
	for(rfs12=0;rfs12<courseStack.length;rfs12++){
		if(courseStack[rfs12]['code'] == code12){
			hascode12 = hascode12 + 1;
			if(courseStack[rfs12]['sec']==sec12){
				remvInd = rfs12;
			}
		}
	}
	
	courseStack.splice(remvInd,1);
	
	if(hascode12 == 1){
		$("#selListItem-"+code12.replace(" ","-")).remove();
	}
	
	$(".block-"+id12).remove();
	
}

function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function weekToNum(we){
	switch(we){
		case 'Mo': return 0;
		case 'Tu': return 1;
		case 'We': return 2;
		case 'Th': return 3;
		case 'Fr': return 4;
		default: return 5;
	}
}

function setupSubCourse(code){
	$("#subscrollpane").empty();
	
	var courses = getXMLbyCode(code);
	
	for(i = 0;i<courses.length;i++){
		var INU = getIdNameUnit(courses[i]);
		var Secs = getSections(courses[i]);
		
		var content = '<h4 align="center">'+
		INU[1]+"</h4>"+
		//INU[2]+" Units"+"<br><br>"+
		'<ui>';
		for(k=0;k<Secs.length;k++){
			content = content +
			'<li class="selectSecs" code="'+INU[0]+'" sec="'+Secs[k]['id']+'" dtime="'+Secs[k]['dateTime']+'" >'+
			Secs[k]['id']+'<br>'+Secs[k]['dateTime']+
			'</li>';
		}
		content +='</ui><br>';
		
		$("#subscrollpane").append('<h3 class="subscroll-itemhead"><a href="#">'+INU[0]+
		'</a></h3><div class="subscroll-item" id="si-'+INU[0]+'">'
		+content+
		'</div>').accordion('destroy').accordion();
	}
	
	$(".subscroll-item").css({
		"font":"0.8em Georgia",
		"height":"150",
		"padding":"15",
		"overflow": "auto",
		"overflow-x": "hidden"
	});
	
	$(".subscroll-itemhead").click(function(e){
		//var div = document.getElementById("si-"+e.target.innerHTML);
	});
	$(".selectSecs").click(function(e){
		var isdopb = addToSelectList($(this).attr('code'),$(this).attr('sec'));
		if(isdopb)
			placeBlock($(this).attr('dtime'),$(this).attr('code'),$(this).attr('sec'));
	});
	$(".selectSecs").css({
		"width":"180",
		"font-size":"0.7em"
	});
	$(".selectSecs").button();
	
}

function layoutSetup(){
	
	$("#tabs").tabs();
	
	$("#subscrollpane").position({
		of: $("#scrollpane"),
		my:"left top",
		at:"right top",
		offset:"0",
		collision:"none"
	});
	
	$("#timetable").position({
		of: $("#subscrollpane"),
		my:"left top",
		at:"right top",
		offset:"40 0",
		collision:"none"
	});
	
	$("#selectList").position({
		of: $("#scrollpane"),
		my: "left top",
		at: "left bottom",
		offset: "0 10",
		collision: "none"
	});
	
	times.push("08:30");
	var idate = iDate(9,0,0);
	var count = 1;
	while(count<28){
		times.push(rDate(idate));
		var idate2 = iDate(idate.getHours(),idate.getMinutes()+20,0);
		var range = rDate(idate)+" - "+rDate(idate2);
		
		var con = '<tr id="time-'+count.toString()+'"><td>'+range+'</td>';
		for(i=0;i<5;i++){
			con += '<td>	</td>';
		}
		con +='</tr>';
		$("#reallytable").append(con);
		
		idate = iDate(idate2.getHours(),idate2.getMinutes()+10,0);
		
		count++;
	}
	
	
	for(i = 0;i<codelist.length;i++){
		$("#scrollpane").append('<div class="scroll-item" id="course-'+codelist[i]+'">'+codelist[i]+'</div>');
	}
	$(".scroll-item").click(function(e){
		setupSubCourse(e.target.innerHTML);
	});
	$(".scroll-item").button();
	setupSubCourse('ACCT');

}

function iDate(h,m,s){
	var di = new Date();
	di.setHours(h);
	di.setMinutes(m);
	di.setSeconds(s);
	return di;
}

function rDate(adate){
	var h = adate.getHours();
	if(h<10){ h = "0"+h.toString();}else{h = h.toString();}
	var m = adate.getMinutes();
	if(m<10){ m = "0"+m.toString();}else{m = m.toString();}
	return h+":"+m;
}

function convertADate(astringa){
	var cad = astringa.match(/\d\d/g);
	var h = cad[0];
	if(astringa.match(/PM/) && h!="12"){
		h = (parseInt(h,10)+12).toString();
	}
	return h+":"+cad[1];
	
}

function convertDate(astring){
	var ts =  astring.match(/\d\d:\d\d(AM|PM)/g);
	var d1 = iDate( ts[0].match(/\d\d/g)[0] , ts[0].match(/\d\d/g)[1] , 0 );
	if(ts[0].match(/(PM)/)){
		d1.sethours(d1.getHours()+12);
	}
	var d2 = iDate( ts[1].match(/\d\d/g)[0] , ts[1].match(/\d\d/g)[1] , 0 );
	if(ts[1].match(/(PM)/)){
		d2.sethours(d2.getHours()+12);
	}
	
	return [d1,d2]
}

function log(msg){
	
	var p = document.getElementById("testp");
	p.innerHTML=msg+"<br>"+p.innerHTML;
	
}

function checkSelected(cscode,cssec){
	var hascode = false;
	for(csi = 0;csi<courseStack.length;csi++){
		if(courseStack[csi]['code'] == cscode){
			hascode = true;
			if(courseStack[csi]['sec']==cssec)
				return [true,true];
		} 
	}
	
	return [false,hascode];
}

function addToSelectList(ccode, csec){
	var checking = checkSelected(ccode,csec);
	if(checking[0]){
		return false;
	}
	
	var co = new Object();
	co['code']=ccode;
	co['sec']=csec
	courseStack.push(co);
	
	if(checking[1]){
		return true;
	}
	
	var ccodeid = ccode.replace(" ","-");
	$("#selectList").append('<div class=selCou id="selListItem-'+ccodeid+'">'+ccode+"</div>")
	
	$(".selCou").click(function(){
		var inputtocc = $(this).attr('id').replace('selListItem-','');
		inputtocc = inputtocc.replace('-',' ');
		disCC(inputtocc);
	});
	$(".selCou").css({
		"padding":"1"
	}).button();
	
	return true;
}

function disCC(code45){
	var xml45 = new XMLHttpRequest();
	xml45.open('GET',"CousDesc/"+code45.substr(0,4)+".xml",false);
	xml45.send();
	var xmlre = xml45.responseXML;
	//document.getElementById("diamsg").innerHTML = "work";

	var courses = xmlre.getElementsByTagName('course');
	var tar45 = null;
	for(i45 = 0;i45<courses.length;i45++){
		if(courses[i45].attributes.getNamedItem('code').value==code45){
			tar45 = courses[i45];
			break;
		}
	}
	var head45 = '<div style="font-size:0.8em">'+tar45.getElementsByTagName('name')[0].textContent+" ("+
				 tar45.getElementsByTagName('unit')[0].textContent+" Units) </div>";
	var content45 = '<div style="font-size:0.65em;"> '+tar45.getElementsByTagName('desc')[0].textContent+'</div>';
	
	$("#diamsg").html(content45);
	
	$("#diamsg").dialog({
		autoOpen:true,
		modal: false,
		width: 450,
		title: head45
	});
	
}

function cLayoutSetup(){
	$("#newpost").button();

	$("#createForm").dialog("destroy");
	$("#createForm").dialog({
		autoOpen: false,
		height: 520,
		width: 400,
		title: "New Post",
		modal: true,
		buttons: {
			"Add new post": function(){
				if($("#icourse").attr('value').substr(0,4)!=$("#codeselect").attr('value')){
					iAlert("Course code Must be matched to "+ $("#codeselect").attr('value')+" XXXX");
				}else{
				$.post('/courses/newpost',{
					name: $("#iname").attr('value'), 
					course: $("#icourse").attr('value'),
					comment: $("#icomment").attr('value')
					}, function(data){});
				$.get('/courses/reload',{selected: $("#codeselect").attr('value')}, function(data){
					document.getElementById("disp").innerHTML = data.toString();
				});
				$(this).dialog("close");
				}
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});
	
	$("#newpost").click(function(e){
		$("#createForm").dialog("open");
	});
	
	
	$.get('/courses/reload',{selected: 'ACCT'}, function(data){
				document.getElementById("disp").innerHTML = data.toString();
	});
	$("#codeselect").change(function(e){
		$.get('/courses/reload',{selected: this.value}, function(data){
				document.getElementById("disp").innerHTML = data.toString();
		});
	});
	
}

$(document).ready(function(){
	/*
	if (typeof document.body.style.MozUserSelect!="undefined")
		document.body.style.MozUserSelect="none"
	else
		document.body.onmousedown=function(){return false};
	*/
	xmlHttp.open('GET',"XML_2013_spring/UST.xml",false);
	xmlHttp.send();
	
	$("#msg").dialog({
		autoOpen: false,
		modal: true,
		buttons:{
			Ok: function(){
				$(this).dialog("close");
			}
		}
	});
	$(".ui-dialog-titlebar").hide();
	
	layoutSetup();
	
	cLayoutSetup();
	
	
	var area = document.getElementById("coursearea");
	area.value = "Under Construction";
	
	var file=document.getElementById("courseinput");
	file.addEventListener('change',readTheFile,false);
	
});